<template>
    <a-modal :confirm-loading="modalOption.loading" :okText="modalOption.okText" @ok="modalOption.onOk"
             @cancel="modalOption.onCancel" :cancelText="modalOption.cancelText" :width="modalOption.width" :visible="visible"
             :title="modalOption.title">
        <a-spin tip="loading" :spinning="loading">
            <div class="container">
                <a-form-model ref="formModel" :label-col="formOption.labelCol" :wrapper-col="formOption.wrapperCol"
                              :layout="formOption.layout" :label-align="formOption.labelAlign" :hide-required-mark="formOption.hideRequiredMark"
                              :rules="formOption.rules" :model="formOption.formData">
                    <a-collapse v-model="activeKey">
                        <!-- 基础信息面板 -->
                        <a-collapse-panel key="1" header="基础信息">
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="品名" prop="name" :wrapper-col="{style:{width:'174px'}}">
                                        <a-select
                                            show-search
                                            :filter-option="$filterOption"
                                            v-model="formOption.formData.name"
                                            placeholder="请选择品名"
                                            @change="materialIdChange"
                                        >
                                            <a-select-option v-for="item in searchSource.materialNameList" :key="item.id" :value="item.name">
                                                {{ item.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="件数" prop="num">
                                        <a-input v-model="formOption.formData.num" placeholder="请输入件数" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="进厂日期" prop="inDate">
                                        <a-date-picker
                                            valueFormat="YYYY-MM-DD"
                                            v-model="formOption.formData.inDate"
                                            :locale="locale"
                                        />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="标准号" prop="standardNumber">
                                        <a-input disabled v-model="formOption.formData.standardNumber" placeholder="请输入标准号" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="流水号" prop="serialNum">
                                        <a-input v-model="formOption.formData.serialNum" @input="serialNumInput" placeholder="请输入流水号" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="进厂编号">
                                        <a-input v-model="formOption.formData.inNo" @input="inNoInput" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="GMP编号">
                                        <a-input v-model="formOption.formData.gmpNo" @input="gmpNoInput" placeholder="请输入GMP编号"/>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="件数结存">
                                        <a-input v-model="formOption.formData.numBalance" disabled />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="数量结存">
                                        <a-input v-model="formOption.formData.quantityStorage" disabled />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="存放类别">
                                        <a-input v-model="formOption.formData.depositType" placeholder="请输入存放类别" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="是否超过半年" :wrapper-col="{style:{width:'174px'}}">
                                            <a-select v-model="formOption.formData.overHalfYear" disabled>
                                            <a-select-option value="是">是</a-select-option>
                                            <a-select-option value="否">否</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="有效期">
                                        <a-input-number placeholder="请输入有效期" v-model="formOption.formData.validityDate" style="width: 100%" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="复验期" prop="recheckDate">
                                        <a-input v-model="formOption.formData.recheckDate" placeholder="请输入复验期" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="来货采收">
                                        <a-input v-model="formOption.formData.reapDate" placeholder="请输入来货采收日期" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="备注">
                                        <a-input v-model="formOption.formData.basicRemark" placeholder="请输入备注" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="部位类别">
                                        <a-input v-model="formOption.formData.partType" placeholder="请输入部位类别" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="YC">
                                        <a-input v-model="formOption.formData.yc" placeholder="请输入YC" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="水分">
                                        <a-input v-model="formOption.formData.water" placeholder="请输入水分" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="毛重" prop="maoWeight">
                                        <a-input v-model="formOption.formData.maoWeight" placeholder="请输入毛重" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="皮重"  prop="piWeight">
                                        <a-input v-model="formOption.formData.piWeight" placeholder="请输入皮重" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="初检扣杂"  prop="firstCheckSub">
                                        <a-input v-model="formOption.formData.firstCheckSub" placeholder="请输入初检扣杂" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                
                                <a-col :span="8">
                                    <a-form-model-item label="初检数量" >
                                        <a-input v-model="formOption.formData.firstCheckNum" @input="firstCheckNumInput" placeholder="请输入初检数量"/>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="GMP数量">
                                        <a-input v-model="formOption.formData.gmpNum" @input="gmpNumInput" placeholder="请输入GMP数量"/>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="未折扣数量">
                                        <a-input v-model="formOption.formData.notDiscountNum" placeholder="请输入未折扣数量" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="GMP数量和定包数量差异">
                                        <a-input v-model="formOption.formData.gmpNumDiff" placeholder="请输入差异" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </a-collapse-panel>
                        <!-- 检验信息面板 -->
                        <a-collapse-panel key="2" header="检验信息" v-if="showOtherPanels">
                            <div v-for="(item, idx) in formOption.formData.medicinalCheckRecordList" :key="idx" style="border: 1px solid #eee; padding: 20px; margin-bottom: 20px;">
                                <a-row :gutter="16">
                                    <a-col :span="8">
                                        <a-form-model-item :wrapper-col="{style:{width:'174px'}}" :label="'检验结果'" :prop="`medicinalCheckRecordList.${idx}.checkResult`" :rules="{ required: true, message: '请选择状态' }">
                                            <a-select v-model="item.checkResult" placeholder="请选择检验结果">
                                                <a-select-option value="国标合格">国标合格</a-select-option>
                                                <a-select-option value="省标合格">省标合格</a-select-option>
                                                <a-select-option value="药典合格">药典合格</a-select-option>
                                                <a-select-option value="不合格">不合格</a-select-option>
                                                <a-select-option value="检验中">检验中</a-select-option>
                                                <a-select-option value="退货">退货</a-select-option>
                                            </a-select>
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item :label="'报告日期'" :prop="`medicinalCheckRecordList.${idx}.reportDate`" :rules="{ required: true, message: '请选择报告日期' }">
                                            <a-date-picker valueFormat="YYYY-MM-DD" v-model="item.reportDate" :locale="locale" placeholder="请选择报告日期" />
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item :label="'报告编号'" :prop="`medicinalCheckRecordList.${idx}.reportNo`" :rules="{ required: true, message: '请输入报告编号' }">
                                            <a-input v-model="item.reportNo" placeholder="请输入报告编号" />
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                                <a-row :gutter="16">
                                    <a-col :span="8">
                                        <a-form-model-item :label="`${item.checkResult||''}取样时间`" :prop="`medicinalCheckRecordList.${idx}.checkTakeDate`" :rules="{ required: true, message: '请选择取样时间' }">
                                            <a-date-picker valueFormat="YYYY-MM-DD" v-model="item.checkTakeDate" :locale="locale" placeholder="请选择取样时间" />
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item :label="`${item.checkResult||''}取样量`" :prop="`medicinalCheckRecordList.${idx}.checkTakeNum`" :rules="{ required: true, message: '请输入取样量' }">
                                            <a-input v-model="item.checkTakeNum" placeholder="请输入取样量" />
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item :label="`${item.checkResult||''}放行时间`" :prop="`medicinalCheckRecordList.${idx}.checkReleaseDate`" :rules="{ required: true, message: '请选择放行时间' }">
                                            <a-date-picker valueFormat="YYYY-MM-DD" v-model="item.checkReleaseDate" :locale="locale" placeholder="请选择放行时间" />
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                                <a-row>
                                    <a-col :span="24" style="text-align:right;">
                                        <a-button v-if="formOption.formData.medicinalCheckRecordList.length>1" type="danger" @click="removeCheckItem(idx)">删除</a-button>
                                    </a-col>
                                </a-row>
                            </div>
                            <a-button type="dashed" style="width: 100%" @click="addCheckItem">
                                <a-icon type="plus" /> 添加检验信息
                            </a-button>
                            <a-row :gutter="16" style="margin-top: 20px;">
                                <a-col :span="8">
                                    <a-form-model-item label="黄曲霉素取样日期">
                                        <a-date-picker valueFormat="YYYY-MM-DD" v-model="formOption.formData.aflatoxinTakeDate"  :locale="locale" placeholder="请选择黄曲霉素取样日期" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="特殊类别请验日期">
                                        <a-date-picker valueFormat="YYYY-MM-DD" v-model="formOption.formData.specialCheckDate"  :locale="locale" placeholder="请选择特殊类别请验日期" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="检验结果/其他">
                                        <a-input v-model="formOption.formData.checkOther" placeholder="请输入检验结果/其他" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="检验结果/水分">
                                        <a-input v-model="formOption.formData.checkWater" placeholder="请输入检验结果/水分" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </a-collapse-panel>
                        <!-- 入库信息面板 -->
                        <a-collapse-panel key="3" header="入库信息" v-if="showOtherPanels">
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="存放地点">
                                        <a-input v-model="formOption.formData.putLocation" placeholder="请输入存放地点" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="供货商">
                                        <a-input v-model="formOption.formData.supply" placeholder="请输入供货商" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="规格" prop="spec">
                                        <a-input v-model="formOption.formData.spec" placeholder="请输入规格" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="备注1">
                                        <a-input v-model="formOption.formData.inRemark" placeholder="请输入备注" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="产地">
                                        <a-input v-model="formOption.formData.origin" placeholder="请输入产地" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="入库数量(kg)" prop="inNumber">
                                        <a-input v-model="formOption.formData.inNumber" @input="inNumberInput" placeholder="请输入入库数量" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row :gutter="16">
                                <a-col :span="8">
                                    <a-form-model-item label="入库件数(件)" prop="inNum">
                                        <a-input v-model="formOption.formData.inNum" placeholder="请输入入库件数" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item label="入库日期" prop="inDate2">
                                        <a-date-picker
                                            valueFormat="YYYY-MM-DD"
                                            v-model="formOption.formData.inDate2"
                                            :locale="locale"
                                            placeholder="请选择入库日期"
                                        />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </a-collapse-panel>
                    </a-collapse>
                </a-form-model>
            </div>
        </a-spin>
        <template slot="footer">
                <a-button size="large" type="primary" @click="modalOption.save">暂存</a-button>
                <a-button size="large" @click="modalOption.onCancel">取 消</a-button>
                <a-popconfirm ok-text="保存" cancel-text="返回" title="请确认信息无误！保存后无法再次编辑库存" @confirm="modalOption.onOk">
                    <a-button size="large" type="primary">确 定</a-button>
                </a-popconfirm>
            </template>
    </a-modal>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import locale from "ant-design-vue/lib/date-picker/locale/zh_CN";
import nextApi from "@/api/nextApi";
import areaJson, {getAreaWords} from "@/utils/area";
import { filter } from "vue/types/umd";

@Component({})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) editId!: string;
    @Prop({default:{}}) formData!: any;
    _hasSetEditForm = false
    _hasSetAddForm = false
    @Watch("visible")
    visibleChange(val) {
        if (val) {
            this.getMaterialList()
            this.showOtherPanels = false;
            this.activeKey = ['1'];
            if (!this.editId) {
                if (!this._hasSetAddForm) {
                    // 彻底清空所有字段，防止编辑数据残留到新增
                    Object.assign(this.formOption.formData, {
                        name: '',
                        num: '',
                        inDate: '',
                        standardNumber: '',
                        serialNum: '',
                        inNo: '',
                        gmpNo: '',
                        numBalance: '',
                        quantityStorage: '',
                        depositType: '',
                        overHalfYear: '',
                        validityDate: '',
                        recheckDate: '',
                        reapDate: '',
                        basicRemark: '',
                        partType: '',
                        yc: '',
                        water: '',
                        maoWeight: '',
                        piWeight: '',
                        firstCheckSub: '',
                        firstCheckNum: '',
                        gmpNum: '',
                        notDiscountNum: '',
                        gmpNumDiff: '',
                        medicinalCheckRecordList: [
                            {
                                checkResult: undefined,
                                reportDate: undefined,
                                reportNo: undefined,
                                checkTakeDate: undefined,
                                checkTakeNum: undefined,
                                checkReleaseDate: undefined,
                            }
                        ],
                        putLocation: '',
                        supply: '',
                        spec: '',
                        inRemark: '',
                        origin: '',
                        inNumber: '',
                        inNum: '',
                        inDate2: '',
                        // ...如有其它字段请补充...
                    });
                    Object.assign(this.formOption.formData, {
                        medicinalCheckRecordList: [
                            {
                                checkResult: undefined,
                                reportDate: undefined,
                                reportNo: undefined,
                                checkTakeDate: undefined,
                                checkTakeNum: undefined,
                                checkReleaseDate: undefined,
                            }
                        ],
                        inNo: (this.formOption.formData.standardNumber || '') + (this.formOption.formData.serialNum || ''),
                        gmpNo: (this.formOption.formData.standardNumber || '') + (this.formOption.formData.serialNum || '')
                        // 其它字段如需重置也可在这里赋值
                    });
                    this.inNoManuallyEdited = false
                    this.gmpNoManuallyEdited = false
                    this.firstCheckNumManuallyEdited = false
                    this.gmpNumManuallyEdited = false
                    this.inNumberManuallyEdited = false
                    this._hasSetAddForm = true
                }
            }
        } else {
            // 关闭弹窗时重置
            this.inNoManuallyEdited = false
            this.gmpNoManuallyEdited = false
            this.firstCheckNumManuallyEdited = false
            this.gmpNumManuallyEdited = false
            this.inNumberManuallyEdited = false
            this._hasSetAddForm = false
        }
    }
    activeKey = ['1']
    loading = false
    disabledEdit = false
    showOtherPanels = false
    inNoManuallyEdited = false
    gmpNoManuallyEdited = false
    firstCheckNumManuallyEdited = false
    gmpNumManuallyEdited = false
    inNumberManuallyEdited = false

    // 监听input事件
    inNoInput(e) {
        if (e && e.target && e.target.value === '') {
            this.inNoManuallyEdited = false;
        } else {
            this.inNoManuallyEdited = true;
        }
    }
    gmpNoInput(e) {
        if (e && e.target && e.target.value === '') {
            this.gmpNoManuallyEdited = false;
        } else {
            this.gmpNoManuallyEdited = true;
        }
    }
    serialNumInput(e) {
        const value = e && e.target ? e.target.value : '';
        this.formOption.formData.serialNum = value;
        if (!this.inNoManuallyEdited) {
            this.formOption.formData.inNo = (this.formOption.formData.standardNumber || '') + value;
        }
        if (!this.gmpNoManuallyEdited) {
            this.formOption.formData.gmpNo = (this.formOption.formData.standardNumber || '') + value;
        }
    }
    @Watch("editId", { immediate: true })
    editIdChange(val) {
        if (val) {
            if (!this._hasSetEditForm) {
                this.formOption.formData = { ...this.formData }
                this._hasSetEditForm = true
            }
            this.modalOption.title = `编辑`;
            this.disabledEdit = true
            this.getInfo()
        } else {
            this.modalOption.title = `新增`;
            this._hasSetEditForm = false
        }
    }

    // @Watch("formOption.formData.standardNumber",{immediate:true})

    //组件配置
    locale = locale;
    modalOption: any = {
        width: "90%",
        title: "新增",
        okText: "保存",
        cancelText: "取消",
        loading: false,
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
        save:() => {
            this.save();
        }
    };

    //表单数据源
    searchSource:any = {
        materialNameList:[]
    }
    //表单配置
    formOption: any = {
        labelCol: { style: { width: "172.5px" } },
        wrapperCol: { style: {width:'calc(100% - 185px)'}},
        layout: "inline",
        labelAlign: "right",
        hideRequiredMark: false,
        formData: {
            name: '',
            num: '',
            inDate: '',
            standardNumber: '',
            serialNum: '',
            inNo: '',
            gmpNo: '',
            numBalance: '',
            quantityStorage: '',
            depositType: '',
            overHalfYear: '',
            validityDate: '',
            recheckDate: '',
            reapDate: '',
            basicRemark: '',
            partType: '',
            yc: '',
            water: '',
            maoWeight: '',
            piWeight: '',
            firstCheckSub: '',
            firstCheckNum: '',
            gmpNum: '',
            notDiscountNum: '',
            gmpNumDiff: '',
            medicinalCheckRecordList: [
                {
                    checkResult: undefined,
                    reportDate: undefined,
                    reportNo: undefined,
                    checkTakeDate: undefined,
                    checkTakeNum: undefined,
                    checkReleaseDate: undefined,
                }
            ],
            putLocation: '',
            supply: '',
            spec: '',
            inRemark: '',
            origin: '',
            inNumber: '',
            inNum: '',
            inDate2: '',
            // ...如有其它字段请补充...
        },
        rules: {
            name: [
                { required: true, message: "请选择品名",trigger:'blur' },
            ],
            num: [
                { required: true, message: "请输入件数",trigger:'blur' },
            ],
            inDate: [
                { required: true, message: "请选择进厂日期",trigger:'blur' },
            ],
            standardNumber: [
                { required: true, message: "请输入标准号",trigger:'blur' },
            ],
            serialNum: [
                { required: true, message: "请输入流水号",trigger:'blur' },
            ],
            recheckDate: [
                { required: true, message: "请输入复验期",trigger:'blur' },
            ],
            state: [
                { required: true, message: "请选择状态",trigger:'blur' },
            ],
            reportDate: [
                { required: true, message: "请选择报告日期",trigger:'blur' },
            ],
            reportNo: [
                { required: true, message: "请输入报告编号",trigger:'blur' },
            ],
            spec: [
                { required: true, message: "请输入规格",trigger:'blur' },
            ],
            inNumber: [
                { required: true, message: "请输入入库数量",trigger:'blur' },
            ],
            inNum: [
                { required: true, message: "请输入入库件数",trigger:'blur' },
            ],
            inDate2: [
                { required: true, message: "请选择入库日期",trigger:'blur' },
            ],
            firstCheckNum: [
                { required: true, message: "请输入初检数量",trigger:'blur' },
            ],
            gmpNum: [
                { required: true, message: "请输入GMP数量",trigger:'blur' },
            ],
            maoWeight: [
                { required: true, message: "请输入毛重",trigger:'blur' },
            ],
            piWeight: [
                { required: true, message: "请输入皮重",trigger:'blur' },
            ],
            firstCheckSub: [
                { required: true, message: "请输入初检扣杂",trigger:'blur' },
            ],
            medicinalCheckRecordList: [
                { required: true, message: "请至少添加一组检验信息", type: 'array', min: 1 }
            ]
        },
    };
    materialIdChange(v){
        this.loading = true
        try {
            let find = this.searchSource.materialNameList.find(item=>item.name === v)
            if(find){
                this.formOption.formData.materialName = find.name
                this.formOption.formData.materialId = find.id
                this.formOption.formData.standardNumber = find.code
                this.formOption.formData.validityDate = find.validDay
                this.formOption.formData.recheckDate = find.reInspection
                // 自动拼接编号（仅ManuallyEdited为false时）
                if (!this.inNoManuallyEdited) {
                    this.formOption.formData.inNo = (find.code || '') + (this.formOption.formData.serialNum || '');
                }
                if (!this.gmpNoManuallyEdited) {
                    this.formOption.formData.gmpNo = (find.code || '') + (this.formOption.formData.serialNum || '');
                }
            }
        }finally {
            this.loading = false
        }
    }
    /**
     * @description 查询成品列表
     * **/
    async getMaterialList(){
       const res = await nextApi.selectMaterialListByType({materialType:'中药材'})
       this.searchSource.materialNameList = res.data
    }
    @Watch("formOption.formData.inDate")
    onInDateChange(val) {
        if (val) {
            this.calculateOverHalfYear(val);
        }
    }

    calculateOverHalfYear(date) {
        const currentDate = new Date();
        const inDate = new Date(date);
        const diffTime = Math.abs(currentDate.getTime() - inDate.getTime());
        const diffMonths = Math.floor(diffTime / (1000 * 60 * 60 * 24 * 30));
        this.formOption.formData.overHalfYear = diffMonths >= 6 ? '是' : '否';
    }

    //查询详情后进行修改
    async getInfo(){
        this.loading = true
        this.formOption.formData = this.formData
        // 防御性处理，保证medicinalCheckRecordList为数组且有一个对象
        if (!this.formOption.formData.medicinalCheckRecordList || !Array.isArray(this.formOption.formData.medicinalCheckRecordList) || this.formOption.formData.medicinalCheckRecordList.length === 0) {
            this.formOption.formData.medicinalCheckRecordList = [
                {
                    checkResult: undefined,
                    reportDate: undefined,
                    reportNo: undefined,
                    checkTakeDate: undefined,
                    checkTakeNum: undefined,
                    checkReleaseDate: undefined,
                }
            ];
        }
        if (this.formOption.formData.inDate) {
            this.calculateOverHalfYear(this.formOption.formData.inDate);
        }

        // 检查基础信息必填字段是否都有值
        const basicRequiredFields = ['name', 'num', 'inDate', 'standardNumber', 'serialNum', 'recheckDate','maoWeight','piWeight','firstCheckSub'];
        const hasAllBasicRequired = basicRequiredFields.every(field => {
            const value = this.formOption.formData[field];
            return value !== undefined && value !== null && value !== '';
        });

        if (hasAllBasicRequired) {
            this.showOtherPanels = true;
            this.activeKey = ['1', '2','3'];
            
        } else {
            this.showOtherPanels = false;
            this.activeKey = ['1'];
        }

        setTimeout(()=>{
            this.loading = false
        },400)
    }
    //提交
    modalOk(){
        (this.$refs.formModel as any).validate(async (valid: boolean) => {
            if (valid) {
                this.modalOption.loading = true;
                try {
                    const {id} = this.formOption.formData
                    if(id){
                        this.formOption.formData.medicinalCheckRecordList = this.formOption.formData.medicinalCheckRecordList.map(item=>{
                            return {
                                ...item,
                                medicinalStockId:id
                            }
                        })
                    }
                    if(this.editId){
                        console.log(this.formOption.formData,'修改')
                        const res = await nextApi.addRawMaterialData(this.formOption.formData)
                        this.$message.success(res.msg)
                        this.$emit("closeModal")
                    }else{
                        console.log(this.formOption.formData,'新增')
                        const res = await nextApi.addRawMaterialData(this.formOption.formData)
                        this.$message.success(res.msg)
                        this.$emit("closeModal")
                    }
                }finally {
                    this.modalOption.loading = false;
                }
            }
        });
    }

    //暂存
    async save(){
        try{
            this.modalOption.loading = true;
            const res = await nextApi.saveRawMaterialData(this.formOption.formData)
            this.$message.success(res.msg)
        }finally{
            this.modalOption.loading = false;
            this.modalOption.onCancel()
        }
    }
    closeModal() {
        this.disabledEdit = false
        this.$emit("closeModal");
    }

    @Watch("formOption.formData", { deep: true })
    onFormDataChange() {
        // 检查基础信息必填字段是否都有值
        const basicRequiredFields = ['name', 'num', 'inDate', 'standardNumber', 'serialNum', 'recheckDate','maoWeight','piWeight','firstCheckSub'];
        const hasAllBasicRequired = basicRequiredFields.every(field => {
            const value = this.formOption.formData[field];
            return value !== undefined && value !== null && value !== '';
        });

        if (!hasAllBasicRequired) {
            this.showOtherPanels = false;
            this.activeKey = ['1'];
            return;
        }

        // 如果所有必填字段都有值，则进行表单验证
        this.validateBasicInfo();
    }

    async validateBasicInfo() {
        try {
            // 根据状态决定是否验证检验信息必填项
            // const fieldsToValidate = ['name', 'num', 'inDate', 'standardNumber', 'serialNum', 'recheckDate'];
            // await (this.$refs.formModel as any).validateField(fieldsToValidate);
            this.showOtherPanels = true;
            // 自动展开检验信息面板
            this.activeKey = ['1', '2','3'];
        } catch (error) {
            this.showOtherPanels = false;
            this.activeKey = ['1'];
        }
    }
    mounted() {
    }
    // 检验信息分组操作
    addCheckItem() {
        if (this.formOption.formData.medicinalCheckRecordList.length <= 5) {
            this.formOption.formData.medicinalCheckRecordList.push({
                state: undefined,
                reportDate: undefined,
                reportNo: undefined,
                takeDate: undefined,
                takeNum: undefined,
                releaseDate: undefined,
            });
        }
    }
    removeCheckItem(idx) {
        if (this.formOption.formData.medicinalCheckRecordList.length > 1) {
            this.formOption.formData.medicinalCheckRecordList.splice(idx, 1);
        }
    }
    firstCheckNumInput(e) {
        if (e && e.target && e.target.value === '') {
            this.firstCheckNumManuallyEdited = false;
        } else {
            this.firstCheckNumManuallyEdited = true;
        }
    }
    gmpNumInput(e) {
        if (e && e.target && e.target.value === '') {
            this.gmpNumManuallyEdited = false;
        } else {
            this.gmpNumManuallyEdited = true;
        }
    }
    inNumberInput(e) {
        if (e && e.target && e.target.value === '') {
            this.inNumberManuallyEdited = false;
        } else {
            this.inNumberManuallyEdited = true;
        }
    }
    @Watch('formOption.formData.maoWeight')
    @Watch('formOption.formData.piWeight')
    @Watch('formOption.formData.firstCheckSub')
    autoCalcNumbers() {
        const { maoWeight, piWeight, firstCheckSub } = this.formOption.formData;
        if (
            maoWeight !== undefined && piWeight !== undefined && firstCheckSub !== undefined &&
            maoWeight !== '' && piWeight !== '' && firstCheckSub !== ''
        ) {
            const calc = Number(maoWeight) - Number(piWeight) - Number(firstCheckSub);
            if (!this.firstCheckNumManuallyEdited) {
                this.formOption.formData.firstCheckNum = calc;
            }
            if (!this.gmpNumManuallyEdited) {
                this.formOption.formData.gmpNum = calc;
            }
            if (!this.inNumberManuallyEdited) {
                this.formOption.formData.inNumber = calc;
            }
        }
    }
}
</script>
<style scoped lang="scss">
.container {
    padding: 0;
    .MR-10 {
        margin-right: 10px;
    }
    .inputs {
        width: 200px;
    }
    .inputs-with-qus{
        width: 173px;
    }
    .tool-bar {
        margin-bottom: 20px;

    }
    .table {
        margin-top: 20px;
    }
}
</style>
